package com.jinglvhuanjing.app;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;

import com.jinglvhuanjing.app.base.CountDownActivity;
import com.jinglvhuanjing.app.utils.ByteUtil;
import com.jinglvhuanjing.app.utils.Constants;
import com.jinglvhuanjing.app.utils.ExecutorProcessPool;
import com.jinglvhuanjing.app.utils.LOG;
import com.jinglvhuanjing.app.utils.SingletonSerl;
import com.jinglvhuanjing.app.utils.SpUtils;
import com.jinglvhuanjing.app.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class GarbageDisposalActivity extends CountDownActivity {

    public static void startActivity(Activity activity) {
        Intent intent = new Intent(activity, GarbageDisposalActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_garbage_disposal;
    }

    @Override
    public void initCountDownText() {
        this.mCountText = findViewById(R.id.count_down);

        findViewById(R.id.back_btn).setOnClickListener(view -> {
            LoginActivity.startActivity(GarbageDisposalActivity.this);
            finish();
        });
    }

    private AppCompatButton mRecoveryBtn, mFoodWasteBtn;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        this.mRecoveryBtn = findViewById(R.id.recovery_btn);
        this.mFoodWasteBtn = findViewById(R.id.food_waste_btn);
        this.initEvent();
        setLeftView();
    }

    private Handler mHandlerGar = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            WasteGradeActivity.startActivity(GarbageDisposalActivity.this);
            finish();
        }
    };

    private void initEvent() {
        this.mRecoveryBtn.setOnClickListener(v -> {
            // 可回收
            ExecutorProcessPool.getInstance().execute(() -> {
                lunxun();

                sleep();
                sleep();
                sleep();

                List<String> list = new ArrayList<>();
                addTK(list, ByteUtil.hexByteToString(SingletonSerl.byte_tk_khs));

                LOG.e(TAG, "可回收 获取投口地址：" + list.toString());
                LOG.e(TAG, "可回收 获取投口地址对应最大距离值的投口");

                String dz_ = getDz(list);
                LOG.e(TAG, "可回收 应开启投口地址为："+dz_);
                if(!StringUtils.isEmpty(dz_)){
                    openDoorFirstOrEnd(dz_, true);

                    StringBuffer buffer = singletonSerl.openDoor(dz_, String_0(Integer.toHexString(closeTime), 4));
                    LOG.e(TAG, "可回收 报文前段地址："+buffer.toString());
                    write(buffer);

                    openDoorFirstOrEnd(dz_, false);
                }
            });
            mHandlerGar.sendEmptyMessage(0);
        });

        this.mFoodWasteBtn.setOnClickListener(v -> {
            // 厨余
            ExecutorProcessPool.getInstance().execute(() -> {
                lunxun();

                sleep();
                sleep();
                sleep();

                List<String> list = new ArrayList<>();
                addTK(list, ByteUtil.hexByteToString(SingletonSerl.byte_tk_cy));

                LOG.e(TAG, "厨余 获取投口地址：" + list.toString());
                LOG.e(TAG, "厨余 获取投口地址对应最大距离值的投口");


                String dz_ = getDz(list);
                LOG.e(TAG, "厨余 应开启投口地址为："+dz_);
                if(!StringUtils.isEmpty(dz_)) {
                    openDoorFirstOrEnd(dz_, true);

                    StringBuffer buffer = singletonSerl.openDoor(dz_, String_0(Integer.toHexString(closeTime), 4));
                    LOG.e(TAG, "厨余 报文前段地址：" + buffer.toString());
                    write(buffer);

                    openDoorFirstOrEnd(dz_, false);
                }

            });
            mHandlerGar.sendEmptyMessage(0);
        });
    }

    /**
     * 开门前，开门后调用
     * @param dz    地址码
     * @param first 是否是开门前
     */
    private void openDoorFirstOrEnd(String dz, boolean first){
        StringBuffer buffer = singletonSerl.openDoorFirstOrEnd(dz, first);
        LOG.e(TAG, first?"开门前指令：":"开门后指令：" + buffer);
        if(!first){
            String openDoorEndIntervalTime = SpUtils.getString(getApplicationContext(), Constants.OPEN_DOOR_END_INTERVAL_TIME, "5000");
            String closeTime = SpUtils.getString(getApplicationContext(), Constants.CLOSE_TIME, "50");
            if(StringUtils.isEmpty(openDoorEndIntervalTime)){
                openDoorEndIntervalTime = "5000";
            }
            if(StringUtils.isEmpty(closeTime)){
                closeTime = "50";
            }
            int intervalTime = Integer.valueOf(openDoorEndIntervalTime) + Integer.valueOf(closeTime);
            LOG.e(TAG, "开门后指令下发延迟时间："+intervalTime+"ms");
            try {
                Thread.sleep(intervalTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        write(buffer);
    }

    /**
     * 根据类型添加投口地址列表
     *
     * @param list
     * @param type
     */
    private void addTK(List<String> list, String type) {

        String s1 = ByteUtil.hexByteToString(SingletonSerl.byte_tk1);
        String s2 = ByteUtil.hexByteToString(SingletonSerl.byte_tk2);
        String s3 = ByteUtil.hexByteToString(SingletonSerl.byte_tk3);
        String s4 = ByteUtil.hexByteToString(SingletonSerl.byte_tk4);
        String s5 = ByteUtil.hexByteToString(SingletonSerl.byte_tk5);

        String tk1 = SpUtils.getString(getApplicationContext(), SingletonSerl.tk_string_start + s1);
        String tk2 = SpUtils.getString(getApplicationContext(), SingletonSerl.tk_string_start + s2);
        String tk3 = SpUtils.getString(getApplicationContext(), SingletonSerl.tk_string_start + s3);
        String tk4 = SpUtils.getString(getApplicationContext(), SingletonSerl.tk_string_start + s4);
        String tk5 = SpUtils.getString(getApplicationContext(), SingletonSerl.tk_string_start + s5);

        if (tk1.equals(type)) {
            list.add(s1);
        }
        if (tk2.equals(type)) {
            list.add(s2);
        }
        if (tk3.equals(type)) {
            list.add(s3);
        }
        if (tk4.equals(type)) {
            list.add(s4);
        }
        if (tk5.equals(type)) {
            list.add(s5);
        }

        for (int i = 0; i < list.size(); i++) {
            // 查询投口对应距离值
            write(singletonSerl.getTK_(list.get(i)));
        }
    }

    private String getDz(List<String> list){
        int jlz_ = -1;
        String dz_ = "";
        for (int i = 0; i < list.size(); i++) {
            String dz = list.get(i);
            int jlz = SpUtils.getInt(getApplicationContext(), SingletonSerl.tk_jlz_string_start+dz, 0);
            if(jlz>jlz_){
                jlz_ = jlz;
                dz_ = dz;
            }
        }
        return dz_;
    }

    @Override
    public void countDownComplete() {
        finish();
    }
}
